<?php
function addIds(& $array, $query) {
    $rs = executeQuery($query);
    while ($row = mysql_fetch_row($rs)) {
        array_push($array, $row[0]);
    }
}

/**
 * Deletes players that are "dead" and have never played a game
 */
function cleanPlayers() {
    $pd = new PlayerDao();
    $pmrDao = new PlayerMatchRecordDao();
    $deadPlayers = $pd->findAllDeadPlayers();
    foreach ($deadPlayers as $player) {
        $pmrs = $pmrDao->findPMRsForPlayer($player);
        if (sizeof($pmrs) == 0) {
			echo "<br />Deleting $player->playerId $player->name";
            $pd->delete($player);
        }
    }
}

/**
 * Deletes teams that are not in any season
 */
function cleanTeams() {
    global $races, $teams;
    $td = new TeamDao();
    $rs = executeQuery("select team_id, fk_season_id from teams left outer join seasons_teams on fk_team_id=team_id where fk_season_id is null");
    while ($row = mysql_fetch_row($rs)) {
    	$id = $row[0];
		$team = $teams->getTeam($id);
		echo "<br />Deleting $team->id $team->name";
		$td->delete($team);
    }
}

/* Main Page */
/* Requires logged in user */
include_once ("includes/init.php");
if (!isCommissioner()) {
    $message = "Permission Denied";
    include ("includes/redirect.php");
    return;
}
$noSeasonChange = true;
include_once ("includes/header.php");

echo<<< EOQ
            <caption><h1>Admin Functions</h1></caption>
        <tr>
          <th align="left">
          	<form method="post">
              <input type="submit" name="cleanPlayers" value="Clean Players"> 
              Removes dead and retired players without any matches
            </form>
          </th>
        </tr>
        <tr>
          <th align="left">
            <form method="post">
              <input type="submit" name="cleanTeams" value="Clean Teams">
				Removes teams that are not in any season
            </form>
          </th>
        </tr>
EOQ;
$cleanPlayers = getParam("cleanPlayers");
if (isset ($cleanPlayers)) {
    echo<<< EOQ
        <tr>
          <td>Cleaning Players<br />
EOQ;
    cleanPlayers();
    echo<<< EOQ
<br /><br />Players Cleaned</td>
        </tr>
EOQ;
}

$cleanTeams = getParam("cleanTeams");
if (isset ($cleanTeams)) {
    echo<<< EOQ
        <tr>
          <td>Cleaning Teams<br />
EOQ;
    cleanTeams();
    echo<<< EOQ
          <br /><br />Teams Cleaned</td>
        </tr>
EOQ;
}

include ("includes/footer.php");
?>

